<!-- 海报配置请参考 https://github.com/jasondu/wxa-plugin-canvas -->
<template>
	<view>
		<view @tap="onCreate">
			<slot></slot>
		</view>
		<we-canvas id="poster" ref="weCanvasRef" @success="onCreateSuccess" @fail="onCreateFail"></we-canvas>
	</view>
</template>

<script>
	import weCanvas from "../index/index";

	export default {
		data() {
			return {
				config: {}
			};
		},
		components: {
			weCanvas
		},
		props: {
			preload: {
				// 是否预下载图片资源
				type: Boolean,
				default: false,
			},
			hideLoading: {
				// 是否隐藏loading
				type: Boolean,
				default: false
			}
		},
		watch: {
			config() {}
		},
		mounted() {
			if (this.preload) {
				this.downloadStatus = 'doing';
				this.$refs.weCanvasRef.downloadResource(this.config).then(() => {
					this.downloadStatus = 'success';
					this.$emit('downloadSuccess');
				}).catch(e => {
					this.downloadStatus = 'fail';
					this.$emit('downloadFail', e);
				});
			}
		},
		methods: {
			once(event, fun) {
				if (typeof this.listener === 'undefined') {
					this.listener = {};
				}
				this.listener[event] = fun;
			},
			downloadResource(reset) {
				return new Promise((resolve, reject) => {
					if (reset) {
						this.downloadStatus = null;
					}
					if (this.downloadStatus && this.downloadStatus !== 'fail') {
						if (this.downloadStatus === 'success') {
							resolve();
						} else {
							this.once('downloadSuccess', () => resolve());
							this.once('downloadFail', e => reject(e));
						}
					} else {
						this.$refs.weCanvasRef.downloadResource(this.config).then(() => {
							this.downloadStatus = 'success';
							resolve();
						}).catch(e => reject(e));
					}
				});
			},

			onCreate(reset = false, config) {
				this.config = config;
				if(!this.hideLoading){
					uni.showLoading({
						title: '生成中',
						mask: true
					});
				}
				return this.downloadResource(typeof reset === 'boolean' && reset).then(() => {
					!this.hideLoading && uni.hideLoading();
					this.$refs.weCanvasRef.createIMG(this.config);
				}).catch(err => {
					!this.hideLoading && uni.hideLoading();
					uni.showToast({
						icon: 'none',
						title: err.errMsg || '生成失败'
					});
					console.error(err);
					this.$emit('fail', err);
				});
			},
			onCreate2(reset = false, config) {
				this.config = config;
				return this.downloadResource(typeof reset === 'boolean' && reset).then(() => {
					this.$refs.weCanvasRef.createIMG(this.config);
				}).catch(err => {
					uni.showToast({
						icon: 'none',
						title: err.errMsg || '生成失败'
					});
					console.error(err);
					this.$emit('fail', err);
				});
			},
			onCreateSuccess(e) {
				this.$emit('success', e);
			},
			onCreateFail(err) {
				this.$emit('fail', err);
			}
		}
	};
</script>
